package com.chunfen.dubbo.protocol.http;

import com.chunfen.dubbo.framework.Invocation;
import com.chunfen.dubbo.provider.LocalRegister;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.Method;
import java.util.Map;

public class HttpServletHandler {

    public void  handler(HttpServletRequest request, HttpServletResponse response){
        // 核心处理 请求， 返回结果

        try {
            InputStream in = request.getInputStream();
            ObjectInputStream ois = new ObjectInputStream(in);

            Invocation invocation = (Invocation) ois.readObject();

            ois.close();

            Class implClass = LocalRegister.get(invocation.getInterfaceName());

            Method method = implClass.getMethod(invocation.getMethodName(), invocation.getParamTypes());

            Map<String, ? extends Serializable> result = (Map<String, ? extends Serializable>) method.invoke(implClass.newInstance(), invocation.getParams());

            OutputStream out = response.getOutputStream();

            ObjectOutputStream oos = new ObjectOutputStream(out);

            oos.writeObject(result);
            oos.flush();
            oos.close();


        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
